use reqwest::Client;
use serde::{Deserialize, Serialize};

use crate::auth::get_app_access_token;
use crate::group::model::GroupMessage;
use crate::model::WebSocketMessage;

mod model;

pub async  fn send_message_group(content: Option<String>, web_socket_message: WebSocketMessage) {
    let token = get_app_access_token().await;
    let group = GroupMessage::new(content, web_socket_message.id, web_socket_message.d.clone().unwrap().id);
    if let Err(_res) = Client::builder()
        .build()
        .expect("Client构建失败！")
        .post(format!("https://api.sgroup.qq.com/v2/groups/{}/messages", web_socket_message.d.clone().unwrap().group_openid.unwrap()))
        .header("Authorization", token)
        .json(&group)
        .send().await {
        println!("发送失败！");
    }
}

pub async fn send_ai_message(content: Option<String>, web_socket_message: WebSocketMessage) {
    match content {
        None => {}
        Some(content) => {
            let content = content.replace("/聊天", "");
            let client = Client::builder().build().expect("Client构建失败！");
            let post = client.post("https://tools.mgtv100.com/external/v1/chat")
                .json(&AiMessage { content })
                .send().await.expect("发送失败！");
            let res = post.json::<AiMessageResult>().await.unwrap();
            send_message_group(Some(res.data.content), web_socket_message).await;
        }
    };

}

pub async fn send_one_message(content: Option<String>, web_socket_message: WebSocketMessage) {
    if let Some(_content) = content {
        let client = Client::builder().build().expect("构建失败！");
        let get = client.get("https://v1.hitokoto.cn").send().await.expect("发送失败！");
        let json = get.json::<OneMessage>().await;
        match json {
            Ok(ok) => {
                println!("{:?}", ok);
                send_message_group(ok.hitokoto, web_socket_message).await;
            }
            Err(_) => {}
        }
    }
}

#[derive(Serialize)]
struct AiMessage {
    pub content: String
}

#[derive(Deserialize)]
struct AiMessageResult {
    pub status: String,
    pub code: i32,
    pub data: AiMessageResultData
}

#[derive(Deserialize)]
struct AiMessageResultData {
    pub id: String,
    pub model: String,
    pub created: i32,
    pub content: String,
}

#[derive(Deserialize, Debug)]
struct OneMessage {
    hitokoto: Option<String>
}